package com.rebate.web.servlet;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.rebate.model.Member;
import com.rebate.service.IBaseService;
import com.rebate.util.MD5Util;
import com.rebate.util.Page;
import com.rebate.util.PageUtils;

@Controller
public class MemberServlet extends BaseServlet{
	
	private String view = "/member/listmember";
	private String editView = "/member/editmember";
	@Autowired
	private IBaseService<Member> memberService;
	
	/**
	 * 会员列表页面
	 * @throws IOException 
	 */
	@RequestMapping(value = "/member/index.htm")
	public String index(HttpServletRequest request,ModelMap model,
			HttpServletResponse response,@ModelAttribute("member") Member member) throws IOException {
		return view;
	}
	
//	/**
//	 * 编辑会员页面初始化
//	 * @throws IOException 
//	 */
//	@RequestMapping(value = "/member/edit.htm")
//	public String editInit(HttpServletRequest request,ModelMap model,
//			HttpServletResponse response,@ModelAttribute("member") Member member) throws IOException {
//		member = memberService.findById(member.getId());
//		model.put("member", member);
//		return editView;
//	}
	
	/**
	 * 更新会员信息
	 * @throws IOException 
	 */
	@RequestMapping(value = "/member/update.htm")
	public void update(HttpServletRequest request,ModelMap model,
			HttpServletResponse response,@ModelAttribute("member") Member member) throws IOException {
		if (StringUtils.isNotBlank(member.getLoginPwd())) {
			member.setLoginPwd(MD5Util.md5Hex(member.getLoginPwd()));
		}
		if(memberService.update(member)) {
			response.getWriter().print(1);
		}else {
			response.getWriter().print(0);
		}
	}
	
	/**
	 * 查询会员列表
	 * @throws IOException 
	 */
	@RequestMapping(value = "/member/list.htm")
	public void getList(HttpServletRequest request,ModelMap model,
			HttpServletResponse response,@ModelAttribute("member") Member member) throws IOException {
		Page<Member> page = PageUtils.getPage(request);
		page = memberService.queryForListPage(page, member);
		print(request, response, page);
	}
	
	/**
	 * remove member
	 * @throws IOException 
	 */
	@RequestMapping(value = "/member/remove.htm")
	public void remove(HttpServletRequest request,ModelMap model,
			HttpServletResponse response,@ModelAttribute("member") Member member) throws IOException {
		if(memberService.delete(member.getId())) {
			response.getWriter().print(1);
		}else {
			response.getWriter().print(0);
		}
	}
}
